package com.chalk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.chalk.common.util.IdGenerator;
import com.chalk.dao.SysRoleDao;
import com.chalk.model.SysRole;
import com.chalk.model.SysRoleMenuRelated;
import com.chalk.service.SysRoleMenuRelatedService;
import com.chalk.service.SysRoleService;
import com.chalk.vo.SysRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 平台角色信息(SysRole)表服务实现类
 *
 * @author maxiaoqiang
 * @since 2019-03-22 17:38:25
 */
@Service
@Transactional
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysRoleMenuRelatedService relatedService;

    /*自定义接口*/

    @Override
    public SysRole getRoleByUser(String userName) {
        return sysRoleDao.getRoleByUser(userName);
    }

    /**
     * 根据主键批量(逻辑)删除
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatchByPrimaryKey(String[] ids) {
        return sysRoleDao.deleteBatchByPrimaryKey(ids);
    }

    @Override
    public List<SysRole> selectUserRoleByMap(Map<Object, Object> param) {
        return sysRoleDao.selectUserRoleByMap(param);
    }

    @Override
    public int insertAndMenu(SysRoleVo param) {
        param.setRoleId(IdGenerator.getIdStr());
        int count = sysRoleDao.insert(param);
        this.insertRoleMenu(param.getRoleId(), param.getMenuIds());
        return count;
    }

    @Override
    public int updateAndMenu(SysRoleVo param) {
        int count = sysRoleDao.updateById(param);
        relatedService.delete(new EntityWrapper<SysRoleMenuRelated>().eq("role_id", param.getRoleId()));
        this.insertRoleMenu(param.getRoleId(), param.getMenuIds());
        return count;
    }


    /**
     * 保存关联权限
     *
     * @param roleId
     * @param menuIds
     */
    private void insertRoleMenu(String roleId, List<String> menuIds) {
        SysRoleMenuRelated related = null;
        for (String menuId : menuIds) {
            related = new SysRoleMenuRelated(roleId, menuId);
            relatedService.insert(related);
        }
    }
}